<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Business;

use Kcdns\Admin\Controller\PublicController;
class Application extends \Service\Common\BaseModel
{
    protected $name = 'business_application';
    
    const TYPE_ZERO = 0;//已提交
    const TYPE_ONE = 1;//预约中
    const TYPE_TWO = 2;//已入驻
    const TYPE_THREE = 3;//已拒绝
   
    const STATUS_LABEL = [
    self::TYPE_ZERO => '已提交',
    self::TYPE_ONE => '预约中',
    self::TYPE_TWO => '已入驻',
    self::TYPE_THREE => '已拒绝',
    ];
    
    public function application($data, $uid)
    {
    	$data = OE('Util')->validate($data, [
    			'type'=>'required;label=入驻类型',
    			'username' => 'required;label=联系人',
    			'mobile' => 'required;label=联系电话',
    			'company' => 'required;label=公司名称',
    			'nature' => 'required;label=入驻性质',
    			'mode' => 'required;label=入驻方式',
    			'make_time'=>'required;label=预约最佳时间',
    			
    			]);
    	$find = M('user')->where(['uid'=>$uid])->find();
    	if (!$find) {
    		throw new \Exception('无效用户');
    	}
    	$result = $this->where(['uid'=>$uid])->find();
    	if ($result) {
    		$save = $this->where(['uid'=>$result['uid']])->save([
    				   'type'=>$data['type'],
    				   'username'=>$data['username'],
    				   'mobile'=>$data['mobile'],
    				   'company'=>$data['company'],
    				   'nature'=>$data['nature'],
    				   'mode'=>$data['mode'],
    				   'make_time'=>$data['make_time'],
    				   
    				]);
    		if ($save === false) {
    			throw new \Exception('修改申请失败');
    		}
    	}else{
    		$insertid = $this->add([
    				   'uid'=>$uid,
    				   'type'=>$data['type'],
    				   'username'=>$data['username'],
    				   'mobile'=>$data['mobile'],
    				   'company'=>$data['company'],
    				   'nature'=>$data['nature'],
    				   'mode'=>$data['mode'],
    				   'make_time'=>$data['make_time'],
    				   'create_time'=>date('Y-m-d H:i:s'),
    				   'status'=>self::TYPE_ZERO
    				]);
    		if (!$insertid) {
    			throw new \Exception('申请失败');
    		}
    	}
    	
    	return true;
    }

    public function applicationData($uid)
    {
    	$result = $this->where(['uid'=>$uid])->find();
    	if ($result) {
    		$result['make_time'] = substr($result['make_time'],0,10);
    		$result['status_label'] = self::STATUS_LABEL[$result['status']];
	    	$type_label = ['个人','企业'];
	    	$result['type_label'] = $type_label[$result['type']];
	    	$nature_label = ['产品代销','公司直营'];
	    	$result['nature_label'] = $nature_label[$result['nature']];
	    	$mode_label = ['推荐产品','自卖产品'];
	    	$result['mode_label'] = $mode_label[$result['mode']];
    	}
    	return (array)$result;
    }
    
}